'use strict';

const db = uniCloud.database();
const collection = db.collection('food-categories');

exports.main = async (event, context) => {
  try {
    // 获取所有分类总数
    const totalResult = await collection.count();
    const total = totalResult.total;
    
    // 获取启用状态的分类数
    const enabledResult = await collection.where({
      status: 1
    }).count();
    const enabledCount = enabledResult.total;
    
    // 获取禁用状态的分类数
    const disabledResult = await collection.where({
      status: 0
    }).count();
    const disabledCount = disabledResult.total;
    
    // 获取最近创建的5个分类
    const recentCategories = await collection
      .orderBy('create_date', 'desc')
      .limit(5)
      .get();
    
    // 获取按状态分组的统计
    const statusStats = {
      total,
      enabled: enabledCount,
      disabled: disabledCount,
      enabledPercentage: total > 0 ? Math.round((enabledCount / total) * 100) : 0
    };
    
    // 获取创建时间分布（按月份）
    const allCategories = await collection.get();
    const monthlyStats = {};
    
    allCategories.data.forEach(category => {
      const createDate = new Date(category.create_date);
      const monthKey = `${createDate.getFullYear()}-${String(createDate.getMonth() + 1).padStart(2, '0')}`;
      
      if (!monthlyStats[monthKey]) {
        monthlyStats[monthKey] = 0;
      }
      monthlyStats[monthKey]++;
    });
    
    // 转换为数组格式
    const monthlyStatsArray = Object.keys(monthlyStats).map(month => ({
      month,
      count: monthlyStats[month]
    })).sort((a, b) => a.month.localeCompare(b.month));
    
    return {
      code: 200,
      message: '统计获取成功',
      data: {
        statusStats,
        recentCategories: recentCategories.data,
        monthlyStats: monthlyStatsArray,
        summary: {
          totalCategories: total,
          enabledCategories: enabledCount,
          disabledCategories: disabledCount,
          lastUpdated: Date.now()
        }
      }
    };
  } catch (error) {
    return {
      code: 500,
      message: '统计获取失败',
      data: null
    };
  }
};